package com.lkd.handler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.emq.Topic;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.service.VendingMachineService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Objects;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-08-20 14:37
 */
@Component
@Topic(TopicConfig.VMS_COMPLETED_TOPIC)
@Slf4j
public class OperationTaskCompleteHandler implements MsgHandler {

    @Autowired
    private VendingMachineService vendingMachineService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void process(String jsonMsg) throws IOException {
        TaskCompleteContract contract = JsonUtil.getByJson(jsonMsg, TaskCompleteContract.class);

        if(StringUtils.isNotBlank(contract.getInnerCode())){
            if(Objects.equals(contract.getTaskType(), VMSystem.TASK_TYPE_DEPLOY)){
                //投放工单，修改数据库售货机状态为运营
                vendingMachineService.update(Wrappers.<VendingMachineEntity>lambdaUpdate()
                        .set(VendingMachineEntity::getVmStatus,VMSystem.VM_STATUS_RUNNING)
                        .eq(VendingMachineEntity::getInnerCode,contract.getInnerCode()));
            }

            else if(Objects.equals(contract.getTaskType(), VMSystem.TASK_TYPE_REVOKE)){
                //撤机工单，修改数据库售货机状态为撤机
                vendingMachineService.update(Wrappers.<VendingMachineEntity>lambdaUpdate()
                        .set(VendingMachineEntity::getVmStatus,VMSystem.VM_STATUS_REVOKE)
                        .eq(VendingMachineEntity::getInnerCode,contract.getInnerCode()));
            }
        }else{
            log.error("消息中不包含售货机code");
        }
    }



}
